package appserver;

import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;

public class AppServerModel implements Model, Observable, Runnable {
	private ArrayList<Observer> observers;
	private Record state;
	private QueueManager manager;
	private Query currentQuery;
	private NetworkClient networkClient;
	
	public AppServerModel (QueueManager manager){
		observers = new ArrayList<Observer>();
		this.manager = manager;
	}
	
	@Override
	public void setDataSource(String filepath) {
		networkClient = new TcpIPClient(filepath);
		networkClient.establishConnection();
	}

	@Override
	public void findText(String textToFind) {
		String result = networkClient.sendWithAnswer(textToFind);
		String resStrings[] = result.split("#");
		state = new Record(Integer.parseInt(resStrings[0]),
							resStrings[1],
							resStrings[2]);
		notifyObservers();
	}
	public Record getCurrentState() {
		return state;
	}
	public void addObserver(Object o) {
		observers.add((Observer)o);
	}
	public void removeObderver(Object o) {
		// TODO Auto-generated method stub
		
	}
	public void notifyObservers() {
		for(Observer o: observers){
			o.update(this);
		}
	}
	@Override
	public void run() {
		while (true) {
			try {
				currentQuery = manager.getQuery();
				this.findText(currentQuery.getQuery());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
